package com.pcbly.web.components.utils;
 
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@SuppressWarnings("unchecked")
public class JsonUtils {
	protected static Log log = LogFactory.getLog(JsonUtils.class);

	protected static String parse = "yyyy-MM-dd";

	protected String getParse() {
		return parse;
	}

	@SuppressWarnings("static-access")
	public void setParse(String parse) {
		this.parse = parse;
	}

	/**
	 * 
	 * @param date
	 *            日期对象
	 * @return
	 */
	static String date2Json(Date date) {
		if (date == null) {
			return "";
		}
		return date2Json(date, parse);
	}

	public static String date2Json(Date date, String parse) {
		if (date == null) {
			return "";
		}
		DateFormat df = new SimpleDateFormat(parse);
		return df.format(date);
	}

	/**
	 * @param obj
	 *            任意对象
	 * @return String
	 */
	
	public static String object2json(Object obj) {
		StringBuilder json = new StringBuilder();
		if (obj == null) {
			json.append("\"\"");
		} else if (obj instanceof Date) {
			json.append("\"").append(date2Json((Date) obj)).append("\"");
		} else if (obj instanceof String || obj instanceof Integer
				|| obj instanceof Float || obj instanceof Boolean
				|| obj instanceof Short || obj instanceof Double
				|| obj instanceof Long || obj instanceof BigDecimal
				|| obj instanceof BigInteger || obj instanceof Byte) {
			json.append(string2Json(obj.toString()));
		} else if (obj instanceof Object[]) {
			json.append(array2json((Object[]) obj));
		} else if (obj instanceof List) {
			json.append(list2json((List<?>) obj));
		} else if (obj instanceof Map) {
			json.append(map2json((Map<?, ?>) obj));
		} else if (obj instanceof Set) {
			json.append(set2json((Set<?>) obj));
		} else {
			json.append(bean2json(obj));
		}
		return json.toString();
	}

	/**
	 * @param bean
	 *            bean对象
	 * @return String
	 */
	static String bean2json(Object bean) {
		StringBuilder json = new StringBuilder();
		json.append("{");
		Field[]field=null;
		try {
			field=ClassUtilsStatic.getDeclaredFieldsOfClass(bean.getClass());
		} catch (Exception e) {
			log.error(e);
		}
		if (field != null) {
			for (int i = 0; i < field.length; i++) {
				try {
					String name = object2json(field[i].getName());
					String value =object2json(ClassUtilsStatic.getBeanFieldValue(bean,field[i].getName())); 
//					log.debug("name:::::::::::"+name);
//					log.debug("value:::::::::::"+value);
					json.append(name);
					json.append(":");
					json.append(value);
					json.append(",");
				} catch (Exception e) {
					log.error(e);
				}
			}
			json.setCharAt(json.length() - 1, '}');
		} else {
			json.append("}");
		}
		return json.toString();
	}

	/**
	 * @param list
	 *            list对象
	 * @return String
	 */
//	@SuppressWarnings("unchecked")
	static String list2json(List<?> list) {
		StringBuilder json = new StringBuilder();
		json.append("{\"dataListGrid\":[");
//		Iterator it=list.iterator();
//		while(it.hasNext()){
//			log.debug(object2json(it.next())); 
//			
//		}
		if (list != null && list.size() > 0) {
			for (Object obj : list) {
				json.append(object2json(obj));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, ']');
			json.append("}");
		} else {
			json.append("]}");
		}
		return json.toString();
	}

	/**
	 * @param array
	 *            对象数组
	 * @return String
	 */
	static String array2json(Object[] array) {
		if (array == null || array.length == 0) {
			return "{}";
		}
		StringBuilder json = new StringBuilder();
		json.append("{");
		if (array != null && array.length > 0) {
			for (Object obj : array) {
				json.append(object2json(obj));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, '}');
		} else {
			json.append("}");
		}
		return json.toString();
	}

	/**
	 * @param map
	 *            map对象
	 * @return String
	 */
	static String map2json(Map<?, ?> map) {
		if (map.isEmpty()) {
			return "{}";
		}
		StringBuilder json = new StringBuilder();
		json.append("{");
		if (map != null && map.size() > 0) {
			for (Object key : map.keySet()) {
				json.append(object2json(key));
				json.append(":");
				json.append(object2json(map.get(key)));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, '}');
		} else {
			json.append("}");
		}
		return json.toString();
	}

	/**
	 * @param set
	 *            集合对象
	 * @return String
	 */
	static String set2json(Set<?> set) {
		if (set.isEmpty()) {
			return "{}";
		}
		StringBuilder json = new StringBuilder();
		json.append("{");
		if (set != null && set.size() > 0) {
			for (Object obj : set) {
				json.append(object2json(obj));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, '}');
		} else {
			json.append("}");
		}
		return json.toString();
	}

	/**
	 * @param s
	 *            参数
	 * @return String
	 */
	 static String string2Json(String s) {
	        StringBuilder sb = new StringBuilder(s.length()+20);
	        sb.append('\"');
	        for (int i=0; i<s.length(); i++) {
	            char c = s.charAt(i);
	            switch (c) {
	            case '\"':
	                sb.append("\\\"");
	                break;
	            case '\\':
	                sb.append("\\\\");
	                break;
	            case '/':
	                sb.append("\\/");
	                break;
	            case '\b':
	                sb.append("\\b");
	                break;
	            case '\f':
	                sb.append("\\f");
	                break;
	            case '\n':
	                sb.append("\\n");
	                break;
	            case '\r':
	                sb.append("\\r");
	                break;
	            case '\t':
	                sb.append("\\t");
	                break;
	            default:
	                sb.append(c);
	            }
	        }
	        sb.append('\"');
	        return sb.toString();
	    }
	static String string2json(String s) {
		if (s == null)
			return "";
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < s.length(); i++) {
			char ch = s.charAt(i);
			switch (ch) {
			case '"':
				sb.append("\"");
				break;
			case '\\':
				sb.append("\\");
				break;
			case 'b':
				sb.append("\b");
				break;
			case 'f':
				sb.append("\f");
				break;
			case 'n':
				sb.append("\n");
				break;
			case 'r':
				sb.append("\r");
				break;
			case 't':
				sb.append("\t");
				break;
			case '/':
				sb.append("/");
				break;
			default:
				if (ch >= '\u0000' && ch <= '\u001F') {
					String ss = Integer.toHexString(ch);
					sb.append("\\u");
					for (int k = 0; k < 4 - ss.length(); k++) {
						sb.append('0');
					}
					sb.append(ss.toUpperCase());
				} else {
					sb.append(ch);
				}
			}
		}
		return sb.toString();
	}

}
